package pe.edu.unmsm.fiee.sispagos.presentacion.controller.login;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Scope;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.HttpSessionContextIntegrationFilter;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.WebAuthenticationDetails;
import org.springframework.security.ui.webapp.AuthenticationProcessingFilter;
import org.springframework.stereotype.Controller;

import pe.edu.unmsm.fiee.sispagos.negocio.modelo.UsuarioDTO;
import pe.edu.unmsm.fiee.sispagos.negocio.servicio.UsuarioService;

@Controller
@Scope("session")
public class LoginController {
	
	private String usunik;
	private String password;
	private Integer anioSeleccionado;
	private Integer mesSeleccionado;
	private List<SelectItem> listaMeses;
	private UsuarioDTO usuario;
	private String rutaRaizServidor;
	private String rutaSoloRaizServidor;
	
	@Resource(name="MyAuthenticationManager")
	private AuthenticationManager authenticationManager;
	
	@Resource
	UsuarioService usuServ;
	
	@PostConstruct
	private void init(){
		setListaMeses(new ArrayList<SelectItem>());
		Calendar fechaActual=new GregorianCalendar();
		setAnioSeleccionado(fechaActual.get(Calendar.YEAR));
		setMesSeleccionado(fechaActual.get(Calendar.MONTH)+1);
		listaMes();
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("anioSeleccionado", getAnioSeleccionado());
		FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("mesSeleccionado", getMesSeleccionado());
	}
	
	public String loginAction(){
		try{
			Authentication aut=validarContextSecurity(getUsunik(), getPassword());
	    	if(aut.isAuthenticated()){	    		
	    		setUsuario(usuServ.obtenerUsuarioxNik(getUsunik()));
	    		HttpSession session=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
				session.setAttribute("usuarioLogueado", getUsuario());
	    		return "adminPrincipal";
	    	}else {
	    		return "error";
			}
		}catch(AuthenticationException e){
			return "error";	}
		
	}
	
	public Authentication validarContextSecurity(String usu, String pas)
	{
		HttpServletRequest request= getRequest();
		UsernamePasswordAuthenticationToken authReq=new UsernamePasswordAuthenticationToken(usu, pas);
    	authReq.setDetails(new WebAuthenticationDetails(request));			    	
    	HttpSession session = request.getSession();

    	session.setAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_USERNAME_KEY, usu);
    	Authentication auth = getAuthenticationManager().authenticate(authReq);
        
    	SecurityContext secCtx = SecurityContextHolder.getContext();	    	
    	secCtx.setAuthentication(auth);
    	session.setAttribute(HttpSessionContextIntegrationFilter.SPRING_SECURITY_CONTEXT_KEY, secCtx);   			    	

    	String urlKey = AbstractProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY;	   
    	//SavedRequest savedRequest = (SavedRequest)session.getAttribute(urlKey);
    	session.removeAttribute(urlKey);
    	return auth ;
	}
	
	private HttpServletRequest getRequest() {
		return (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
	}
	
	public void cerrarSesion(ActionEvent event)throws Exception{
		String out=cerrarSesionGeneric();
	}
	
	public String cerrarSesionGeneric() {
		try {
			HttpSession se2=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
	    	se2.invalidate();			
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "error";
	}
	
	private List<SelectItem> listaMes() {	
		listaMeses.clear();
		listaMeses.add(new SelectItem(-1, "Seleccione Mes"));
		listaMeses.add(new SelectItem(1, "Enero"));
		listaMeses.add(new SelectItem(2, "Febrero"));
		listaMeses.add(new SelectItem(3, "Marzo"));
		listaMeses.add(new SelectItem(4, "Abril"));
		listaMeses.add(new SelectItem(5, "Mayo"));
		listaMeses.add(new SelectItem(6, "Junio"));
		listaMeses.add(new SelectItem(7, "Julio"));
		listaMeses.add(new SelectItem(8, "Agosto"));
		listaMeses.add(new SelectItem(9, "Setiembre"));
		listaMeses.add(new SelectItem(10, "Octubre"));
		listaMeses.add(new SelectItem(11, "Noviembre"));
		listaMeses.add(new SelectItem(12, "Diciembre"));		
		return listaMeses;
	}
	
	public static String obtenerRutaRaiz(HttpServletRequest request){
		String rutaRaiz;
		rutaRaiz=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
		return rutaRaiz;
	}
	
	
	/***************************GETTERS AND SETTERS*********************************/
	public String getUsunik() {
		return usunik;
	}
	public void setUsunik(String usunik) {
		this.usunik = usunik;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getAnioSeleccionado() {
		return anioSeleccionado;
	}

	public void setAnioSeleccionado(Integer anioSeleccionado) {
		this.anioSeleccionado = anioSeleccionado;
	}

	public Integer getMesSeleccionado() {
		return mesSeleccionado;
	}

	public void setMesSeleccionado(Integer mesSeleccionado) {
		this.mesSeleccionado = mesSeleccionado;
	}

	public List<SelectItem> getListaMeses() {
		return listaMeses;
	}

	public void setListaMeses(List<SelectItem> listaMeses) {
		this.listaMeses = listaMeses;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	public UsuarioDTO getUsuario() {
		return usuario;
	}

	public void setUsuario(UsuarioDTO usuario) {
		this.usuario = usuario;
	}

	public String getRutaRaizServidor() {
		FacesContext context=FacesContext.getCurrentInstance();
		HttpServletRequest request=(HttpServletRequest)context.getExternalContext().getRequest();
		rutaRaizServidor=obtenerRutaRaiz(request);
		return rutaRaizServidor;
	}

	public void setRutaRaizServidor(String rutaRaizServidor) {
		this.rutaRaizServidor = rutaRaizServidor;
	}

	public String getRutaSoloRaizServidor() {
		FacesContext context=FacesContext.getCurrentInstance();
		HttpServletRequest request=(HttpServletRequest)context.getExternalContext().getRequest();
		rutaSoloRaizServidor=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
		return rutaSoloRaizServidor;
	}

	public void setRutaSoloRaizServidor(String rutaSoloRaizServidor) {
		this.rutaSoloRaizServidor = rutaSoloRaizServidor;
	}

}
